//
// Directory.cpp
// Usage: VFS directory object
// CreateDate: 2009-05-19
// Author: MaJiuyue
//
#include "Directory.h"

Directory::Directory(const char *name, u32 inode, size_t length, FileSystem * fs)
	: File(name, inode, length, fs, FT_DIRECTORY)
{
	m_MountPoint = NULL;
}

Directory::~Directory()
{
	m_Entrys.iterateFirst();
	while(m_Entrys.iterateIsValid())
	{
		delete m_Entrys.iterateGetValue();
		m_Entrys.iterateNext();
	}
}

int Directory::AddEntry(File * entry)
{
	Directory * target = NULL;

	if(this->m_MountPoint!=NULL)
		target = m_MountPoint;
	else
		target = this;

	// Check if have same name
	target->m_Entrys.iterateFirst();
	while(target->m_Entrys.iterateIsValid())
	{
		if(strcmp(name, entry->GetFileName())==0)
			return -EEXIST;
		target->m_Entrys.iterateNext();
	}

	// Add entry
	target->m_Entrys.insertLast(entry);

	return 0;
}

File * Directory::GetEntry(int index)
{
	Directory * target = NULL;

	if(this->m_MountPoint!=NULL)
		target = m_MountPoint;
	else
		target = this;

	if(target->m_Entrys.getLength()==0)
	{
		panic("Directory empty! should read from fs!");
	//	return fs->readdir(inode, index);
	}

	if(index>=target->m_Entrys.getLength())
		return NULL;
	
	target->m_Entrys.iterateFirst();
	for(int i=0; i<index; i++)
		target->m_Entrys.iterateNext();

	return target->m_Entrys.iterateGetValue();
}

int Directory::GetEntryCount()
{
	Directory * target = NULL;

	if(this->m_MountPoint!=NULL)
		target = m_MountPoint;
	else
		target = this;

	return target->m_Entrys.getLength();
}

int Directory::Mount(Directory *target)
{
	if(target->m_MountPoint!=NULL)
		return EEXIST;

	if(target->GetType()!=FT_DIRECTORY)
		return ENOTDIR;
	target->m_MountPoint = this;
	return 0;
}

void Directory::Unmount()
{
	panic("Umount not implement!");
}

int Directory::read(int off, size_t size, addr_t buf)
{
	return 0;
}

int Directory::write(int off, size_t size, addr_t buf)
{
	return 0;
}

